package com.zjp.controller;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.zjp.service.ProductService;
import com.zjp.vo.Product;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RestController
@RequestMapping("/prodcut")
public class ProductController {
    @Resource
    private ProductService productService;

    @Resource
    private DiscoveryClient client;// 进行Eureka的发现服务


    @RequestMapping("/discover")
    public Object discover() { // 直接返回发现服务信息
        return this.client;
    }

    /**
     * 异常处理
     *
     * @param id
     * @return
     */
    public Object getFallback(@PathVariable("id") long id) {
        Product product = new Product();
        product.setProductName("HystrixName");
        product.setProductDesc("HystrixDesc");
        product.setProductId(0L);
        return product;
    }


    @RequestMapping(value = "/get/{id}")
    @HystrixCommand(fallbackMethod = "getFallback") //出现异常进入熔断方法
    public Object get(@PathVariable("id") long id) {

        Product product = this.productService.get(id);
        if (product == null) {
            throw new RuntimeException("该产品已下架!");
        }
        return product;
    }

    @RequestMapping(value = "/add")
    public Object add(@RequestBody Product product) {
        return this.productService.add(product);
    }

    @RequestMapping(value = "/list")
    @HystrixCommand
    public Object list() {
        return this.productService.list();
    }

}
